var tree = layui.tree
    ,layer = layui.layer
    ,table = layui.table
    ,$ = layui.jquery,form=layui.form,laytpl=layui.laytpl
    ,associatedid=""
    ,associatedname=""
    ,dcode="";
var data=[];
var data1=[];
let isContainsRoleUser=false;
is_contains_role_user();

queryall();
//getuserByDepartmentCode();
var data2 = [];
var selectuserdata = {userid:"121212",chinesesign:"statics/images/layui-logo.jpg"};
tree.render({
    elem: '#usermenu' //默认是点击节点可进行收缩
    ,data: data
    ,showLine:false
    ,click: function(obj){
        //obj.data.id为点击左边导航的ID 查询后刷新表格
        dcode=obj.data.code;
        getuserByDepartmentCode(obj.data.code,"");
      /* getuserByDepartmentCode(obj.data.code);
       table.reload('userdettingstableid',{});
        table.render({});*/
        //执行重载
        table.reload('userdettingstableid', {
            data:data1
            ,page: {
                curr: 1 //重新从第 1 页开始
            }
           /* ,where: {
                key: {
                    departmentCode:obj.data.code
                }
            }*/
        }, 'data');
    }
});
table.render({
    elem: '#userdettingsid'
    ,data:data1
    ,toolbar: '#toolbarDemo'
    ,cols: [[
        {checkbox: true, fixed: true}
        ,{field:'id', width:50, fixed: true, hide:true}
        ,{field:'departmentCode',fixed:true, hide:true}
        ,{field:'name', title:'用户名称', fixed: true,width:150}
        ,{field:'code', title:'用户编码', sort: true, width:150}
        ,{field:'roles', title:'角色', fixed: true, width:200}
        ,{field:'msn', title:'是否管理层', fixed: true, width:100}
        ,{field:'right', title:'关联',align: 'center',toolbar:'#usererelevance', width:150}
        ,{fixed: 'right', width:280, align:'center', toolbar: '#usereditor', title:'操作'}
    ]]
    ,id: 'userdettingstableid'
    ,height: $(document).height() - $('#userdettingsid').offset().top - 50
    ,page: true
});
table.on('toolbar(userdettingstable)', function(obj){
    var checkStatus = table.checkStatus(obj.config.id);
    var data = checkStatus.data;
    switch(obj.event){
        case 'neweuser':
            if(dcode=="") {
                layer.msg("请选择所属部门!");
                break;
            }
            parent.intab("views/jsp/SystemCenter/tpl/newupuser.jsp?dcode="+dcode,"新增用户");
            break;
        case 'upDatePsw':
            if(data.length!=1){
                layer.msg("请选择一个用户");
                break;
            }
            let userCode=data[0].code;
            let userName=data[0].name;

            //iframe层-父子操作
            layer.open({
                type: 1,
                area: ['500px', '300px'],
                btn: ['确定', '关闭'],
                title :'修改密码',
                fixed: false, //不固定
                content:  $("#upDatePswDiv"),
                success: function(index, layero){ //层弹出后的成功回调方法
                    $("#userCode").val(userCode)
                    $("#userName").val(userName)
                },
                yes: function(index, layero){
                    //修改秘密并保存
                    let newPassword=$("#newPassword").val()
                    let flag=updateUserPsw(userCode,newPassword);
                    if (flag){
                        layer.msg("修改成功")
                        layer.close(index); //如果设定了yes回调，需进行手工关闭
                    }else {
                        layer.msg("修改失败")
                    }

                }
            });
            break;
        case 'deleteuser':
            if(data.length==0){
                layer.msg("请选择要删除的用户");
                break;
            }
            var delid = [];
            for (var i = 0;i<data.length;i++){
                delid.push(data[i].id)
            }
            var num=delUser(delid);
            if(num < 10000 && num >0){
                layer.msg("删除成功!");
            }else if(num <10000 && num ==0){
                layer.msg("本地删除失败!");
                break;
            }else if(num >10000){
                layer.msg("同步云枢删除失败!");
                break;
            }
            /*layer.msg('需要删除的数据ID为：'+ JSON.stringify(delid) + ',执行删除');
            table.reload('userdettingstableid',{}); //ajax删除成功之后刷新表格*/
            searchs();
            break;
        case 'searchs':
            searchs();
            break;
            /*var username = $('#username').val();
            if(dcode=="") break;
           // layer.msg("搜索");
            getuserByDepartmentCode(dcode,username);
            //执行重载
            table.reload('userdettingstableid', {
                data:data1,
                page: {
                    curr: 1 //重新从第 1 页开始
                }
                /!*,where: {
                    key: {
                        name: username
                    }
                }*!/
            }, 'data');
            break;*/
    };
});

//监听工具条
table.on('tool(userdettingstable)', function(obj){
    var data = obj.data;
    if(obj.event === 'detail'){
       // var src=getFtpPath(ftpPath,fileName);
        //layer.msg('ID：'+ data.id + ' 的查看操作');
       // selectuser(data);
        //正式环境下 selectuserdata为ajax获取的数据
        var getTpl = selectuserhtml.innerHTML
            ,selectuser = document.getElementById('selectuser');
        laytpl(getTpl).render(data, function(html){
            selectuser.innerHTML = html;
        });
        layer.open({
            type: 1,
            title: "查看用户信息",
            area: ['710px', '340px'],
            content: $("#selectuser")//引用的弹出层的页面层的方式加载修改界面表单
        });
    } else if(obj.event === 'del'){
        layer.confirm('真的删除吗？', function(index){
            //需要删除的ID：data.id
            var ids=[];
            ids.push(obj.data.id);

            var num=delUser(ids);
            if(num < 10000 && num >0){
                layer.msg("删除成功!");
            }else if(num <10000 && num ==0){
                layer.msg("本地删除失败!");

            }else if(num >10000){
                layer.msg("同步云枢删除失败!");

            }
           /* if(delUser(ids)){
                searchs();
                layer.msg("删除成功", {icon: 6});
            }else{
                layer.msg("删除失败!", {icon: 6});
            }*/
           /* obj.del();
            layer.msg("删除成功", {icon: 6});
            layer.close(index);
            table.reload('charactertableid',{}); //ajax删除成功之后刷新表格*/
        });
    } else if(obj.event === 'edit'){
        parent.intab("views/jsp/SystemCenter/tpl/newupuser.jsp?usercode="+data.code,"修改用户")
    } else if(obj.event === 'erelevance'){
       associatedid = data.code;
        associatedname=data.name;
        /*  layer.msg('ID：'+ data.id + ' 的关联操作');*/
        getData2();
        layer.open({
            type: 1,
            title: "关联账号",
            area: ['710px', '420px'],
            content: $("#erelevance")//引用的弹出层的页面层的方式加载修改界面表单
        });
        table.reload('erelevancetableid', {
           /* data:data2,*/

            url:'account/getAllAccount'
        }, 'data');

    }else if(obj.event === 'qxglzh'){
       //var userrcode=obj.data.code;//用户code

        if(updateAccount("","",obj.data.code)){
            layer.msg("取消帐号关联成功！");
        }
    }
});
//关联帐号
table.render({
    elem: '#erelevanceid'
    //,data:data2

    ,url:'account/getAllAccount'
    ,cols: [[
        {field:'radio', width:85, templet: function (d) {
                if (d.usercode == "" || d.usercode==null) {
                    return '<div><input type="radio" name="radio" value="'+d.code+'" class="layui-table-link"></div>'
                } else {
                    return '<span ></span>'
                }

            }}
        ,{field:'code', title:'默认登录名', fixed: true}
        ,{field:'name', title:'关联用户', fixed: true}
    ]]
    ,id: 'erelevancetableid'
    ,height: 300
    ,page: false
});
form.render('radio');
$("#erelevancetj").on('click',function () {
    var checkeds = $("input[name='radio']:checked").val();
    if(updateAccount(checkeds,associatedname,associatedid)){
        layer.msg("关联成功！");
        layer.closeAll();
        searchs();
    }else{
        layer.msg("关联失败！");
    }

    /*layer.closeAll();
    layer.msg("关联用户ID"+associatedid+'选中了账号：ID为'+ checkeds);*/
})

//批量删除
function delUser(ids) {
    var tf=false;
    $.ajax({
        type : 'POST',
        //  url : 'resource/getTree',
        data:{"ids":JSON.stringify(ids)},
        url:'user/deleteByIDS',
        dataType:"json",
        /*  contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                //tf=true;
                tf=da.data;
            }
        },
        error: function(data) {
           // layer.msg("获取失败!");
        }
    });
    return tf;
}
//搜索
function searchs() {
    var username = $('#username').val();
    if(dcode=="") return;
    // layer.msg("搜索");
    getuserByDepartmentCode(dcode,username);
    //执行重载
    table.reload('userdettingstableid', {
        data:data1,
        page: {
            curr: 1 //重新从第 1 页开始
        }
        /*,where: {
            key: {
                name: username
            }
        }*/
    }, 'data');

}
//获取组织机构树
function queryall() {
    $.ajax({
        type : 'POST',
        //  url : 'resource/getTree',
        url:'department/selectTree',
        dataType:"json",
        contentType: 'application/json',
        async:false,
        success : function (da) {
            if(da.status==200 ){
                // datas=da.data
                // datas=da.data;
                // datas[0]=da.data;
                var dat=da.data;
                var obj={};
                obj.id=dat.id;
                obj.code=dat.code;
                obj.name=dat.name;
                obj.desc=dat.desc;
                obj.createTime=dat.createTime;
                obj.creator=dat.creator;
                obj.pid=dat.pid;
                obj.companyCode=dat.companyCode;
                obj.users=dat.users;
                obj.list=initData(dat.list);
                obj.children=obj.list;
                obj.title=obj.name;
                obj.field="";
                data.push(obj);
                // datas= initData(data.list);
            }
        },
        error: function(data) {
            layer.msg("初始化失败!");
        }
    });
}
function initData(data) {
    var object=[];
    for(var i=0;i<data.length;i++){
        var obj={};
        obj.id=data[i].id;
        obj.code=data[i].code;
        obj.name=data[i].name;
        obj.desc=data[i].desc;
        obj.createTime=data[i].createTime;
        obj.creator=data[i].creator;
        obj.companyCode=data[i].companyCode;
        obj.users=data[i].users;
        obj.title=obj.name;
        obj.field="";
        if(data[i].list != null){
            obj.list=initData(data[i].list);
        }
        obj.children=obj.list;

        object.push(obj);
    }

    return object;
}
//获取部门下员工
function getuserByDepartmentCode(dcode,name) {

    $.ajax({
        type : 'POST',
        //  url : 'resource/getTree',
        data:{"departmentCode":dcode,"name":name},
        url:'user/selectByDcode',
        dataType:"json",
        /*  contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                var data=da.data;
                data1=getData1(data);

            }
        },
        error: function(data) {
            layer.msg("获取失败!");
        }
    });
}
function getData1(data) {
    var object=[];
    for(var i=0;i<data.length;i++){
        var obj={};
        obj.id=data[i].id;
        obj.departmentCode=data[i].departmentCode;
        obj.name=data[i].name;
        obj.code=data[i].code;
        obj.roles=data[i].roles;
        obj=data[i];
        object.push(obj);
    }
return object;
}
//关联
function getData2() {
    $.ajax({
        type : 'POST',
        //  url : 'resource/getTree',
       // data:{"departmentCode":dcode,"name":name},
        url:'account/getAllAccount',
        dataType:"json",
        /*  contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                data2=da.data;
            }
        },
        error: function(data) {
            layer.msg("获取失败!");
        }
    });
}
function  updateAccount(code,name,usercode) {
    var tf=false;
    $.ajax({
        type : 'POST',
        //  url : 'resource/getTree',
        data:{"code":code,"name":name,"usercode":usercode},
        url:'account/updateAccountAndUser',
        dataType:"json",
        /*  contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf=true;
            }
        },
        error: function(data) {
            layer.msg("获取失败!");
        }
    });
    return tf;
}

//判断该用户是否拥有 用户设置删除按钮显示(YHSZSCANXS001)  角色 true:是 false 否
function is_contains_role_user() {
    $.ajax({
        url: 'user/isContainsRoleUser',
        async: false,
        success: function (da) {
            if (da.status == 200) {
                isContainsRoleUser = da.data;
            }
        }
    });
}

//修改秘密并保存
function updateUserPsw(userCode,newPassword) {
    let flag=false;
    let encrypt = new JSEncrypt();
    $.ajax({
        type: 'POST',
        datatype: 'text',
        url:  'codec/getPublicKeyString',
        async:false,
        success: function (data) {
            if (data.status == 200) {
                encrypt.setPublicKey(data.data);
            }
        }
    });

    var password=encrypt.encrypt(newPassword);
    $.ajax({
        type : 'POST',
        data:{
            "code":userCode,
            "password":$.md5(newPassword),
            "pwd":password
        },
        url:'account/updateAccount',
        dataType:"json",
        async:false,
        success : function (da) {
            if(da.status==200){
                 flag=true;
            }
        }
    });
    return flag;
}